﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;

namespace Scala.Logic.Services
{
    public class XMLService
    {
        public XMLService()
		{
		}        

        private XmlSchemaSet CreateValidator()
        {
            XmlSchemaSet schemas = new XmlSchemaSet();
            schemas.Add("", XmlReader.Create(new StringReader(Resources.Export)));
            return schemas;
        }

        public bool Validate(XDocument element)
        {
            bool hasErrors = false;            
            element.Validate(CreateValidator(), (sender, e) =>
            {
                Console.WriteLine(e.Message);
                hasErrors = true;
            }, true);
            return hasErrors;
        }

        public XDocument SerializeToXML(List<Event> events)
        {
            XDocument document = new XDocument(
                new XComment("Export to remote host"));

            XNamespace nSpace = "http://scala.project";
            XElement xmlTree = new XElement(nSpace + "Events");

            foreach (var instance in events)
            {
                XElement xmlEvent = new XElement("Event",
                
                    new XElement("Id", instance.Id),
                    new XElement("Title", instance.Title),
                    new XElement("EventType", instance.EventType.Id),
                    new XElement("FromDate", instance.FromDate),
                    new XElement("TillDate", instance.TillDate)
                );

                if (!String.IsNullOrEmpty(instance.Place))
                    xmlEvent.Add(new XElement("Place", instance.Place));

                xmlTree.Add(xmlEvent);
            }

            document.Add(xmlTree);
            return document;
        }      
    }
}
